<?php
/**
* checkin.php
*/
session_start();
include_once("config/config.inc.php");
include_once("Reporting.php");
include_once("currentcash.function.php");

$user = $_SESSION["hotel"]["userid"];

function getshift($date) {
	list($d, $t) = explode(" ", $date);
	list($h, $m, $s) = explode(":", $t);
	$sql = "select shift_id from shifts where $h between shift_start and shift_end";
	$res = mysql_query($sql) or die(mysql_error());
	list($shift)=mysql_fetch_row($res);
	if($h==16)
	{
		$shift = 3;
	}
	elseif($h==8)
	{
		$shift = 2;
	}
	return  $shift;
}

function getunitprice($item) {
	$sql = "select sas_amount from sales_and_services where sas_id='$item'";
	$res = mysql_query($sql) or die(mysql_error());
	$row = mysql_fetch_row($res);
	return $row[0];
}



if($_POST["act"]=="newcheckin") 
{
	
	reset($_POST);
	foreach($_POST as $key => $value) 
	{
		${$key}=$value;
	}
	//echo "entering..";
	$user = $_SESSION["hotel"]["userid"];
	//echo $user;
	//update occupancy  -- $room, $rate, act_checkin, ext_checkout,  discount,  adjustment
	$now = date("Y-m-d H:i:s");
    $shift = getshift($now); 
	$new_checkin=$now;
	$duration = $new_duration * 24 + $new_halfduration *12 + $new_extension + $hidden_duration;
	
	if($duration) {
		$indate = new DateTime($new_checkin);
		$newcheckout = date_add($indate, new DateInterval("PT".$duration."H") );
		$newcheckout = $indate->format("Y-m-d H:i:s");
	}
//die(" $new_duration * 24 + $new_halfduration *12 + $new_extension + $hidden_duration; ". $duration .' '. $newcheckout);
	if(!isRoomOccupied($newroomid))
	{
	$sql = "insert into occupancy(room_id, actual_checkin, expected_checkout, rate_id, update_by, shift_checkin) 
		values ('$newroomid','$new_checkin','$newcheckout', '$newrateid','$user', '$shift' ) ";
	//echo $sql;
	$res = mysql_query($sql) or die($sql);
	//echo $sql;
	$newoccupancy = mysql_insert_id();
	//log this 
	$sql = " insert into occupancy_log(transaction_date, occupancy_id, update_by, remarks, transaction_type ) value ('$now', '$newoccupancy', '$user', '', 'CheckIn' ) ";
	mysql_query($sql) or die($sql);
	//update room status;
	$sql = " update rooms set status=2, last_update='$now',update_by='$user' where room_id='$newroomid' ";
	mysql_query($sql) or die($sql);
	//insert room log
	$sql = " insert into room_log (room_id,	status_id, update_date, update_by, remarks) values
			('$newroomid', '2', '$now', '$user', 'Standard CheckIn, $new_duration days, $new_extension extension')
	";
	mysql_query($sql) or die($sql);
	//if guest id is present
	if($new_guestid) {
		$sql = " insert into guest_history (guest_id, occupancy_id) values ($new_guestid, $newoccupancy) ";
		mysql_query($sql);
	}
	
	// insert  salestransaction details
	// room sales --> category 3
	// standard room charge item_id=15
	
	$remarks = ($_POST["management_endorsement"]=='on') ? 'Management Endorsement' : 'Regular';
	//if reservation claimed
	if($reservecode) {
		$remarks.=" Reservation Code: $reservecode, Deposit Claimed: $reservedeposit";
		$sql  ="insert into reservation_transactions(transaction_date,reservation_code, occupancy_id, amount_claimed,update_by )
			values('$now', '$reservecode','$newoccupancy','$reservedeposit','$user');
		" ;
		mysql_query($sql);
		//save to salesreceipts as claimed deposit
		$sql = " insert into salesreceipts(receipt_date, occupancy_id, tendertype, amount, update_by) 
				values ('$now', '$newoccupancy', 'Reservation Fee', '$reservedeposit','$user')";
		mysql_query($sql) or die(mysql_error());
		$sql= "update reservations set status='Claimed',date_updated='$now',updated_by='$user'
			where reserve_code='$reservecode'";
		mysql_query($sql) or die(mysql_error());
	}
	$sql  =" insert into room_sales( occupancy_id, sales_date, category_id, item_id , unit_cost, qty, update_date, remarks,update_by,room_id) 
			values ( '$newoccupancy', '$now', 3, 15, '$new_rate',1,'$now','$remarks','$user','$newroomid') ";
	mysql_query($sql);
	
	// discount
	if($new_discount)
	{
		$new_discount = -1 * $new_discount;
		$sql  =" insert into room_sales( occupancy_id, sales_date, category_id, item_id ,  unit_cost, qty,update_date,remarks,update_by,room_id) 
			values ('$newoccupancy', '$now', 3,17,'$new_discount','1','$now','$remarks','$user','$newroomid') ";
		mysql_query($sql);
		//discount_log
		$sql = "insert into discount_log (occupancy_id, discount_given, oic, reason, update_date, remarks,update_by) values 
				('$newoccupancy', '$new_discount', '$oic', '$new_reason', '$now','$remarks','$user');
			";
		mysql_query($sql);
	}
	
	
	
	if(isset($_POST['xtra_11']) && $_POST['xtra_11'] > 0) {
		$newunitprice=getunitprice(11);
		$val= $_POST['xtra_11'];
		$itemid=11;
		$sql = "insert into room_sales (sales_date, order_code, occupancy_id, category_id, item_id,  unit_cost, qty, update_date,update_by,room_id)
		values ('$now', '0', '$newoccupancy', '1' ,'$itemid', '$newunitprice' ,'$val','$now','$user','$newroomid' )";
		mysql_query($sql) or die($sql . mysql_error()) ; 
		$print=true;
	}
	
	if($new_duration > 0) {
		for($x=1; $x <= $new_duration;$x++) {
			$indate =  new DateTime($now);
			$mynewcheckout = date_add($indate, new DateInterval("P".$x."D") );
			$mynewcheckout = $indate->format("Y-m-d H:i:s");
			$sql  =" insert into room_sales( occupancy_id, sales_date, category_id, item_id , unit_cost, qty, update_date, remarks,update_by,room_id) 
			values ( '$newoccupancy', '$mynewcheckout', 3, 15, '$new_rate',1,'$now','$remarks','$user','$newroomid') ";
			mysql_query($sql) or die($sql);	
			
			// discount
			if($new_discount)
			{
				//$new_discount = -1 * $new_discount;
				$sql  =" insert into room_sales( occupancy_id, sales_date, category_id, item_id ,  unit_cost, qty,update_date,remarks,update_by,room_id) 
					values ('$newoccupancy', '$mynewcheckout', 3,17,'$new_discount','1','$now','$remarks','$user','$newroomid') ";
				mysql_query($sql);
				//discount_log
				$sql = "insert into discount_log (occupancy_id, discount_given, oic, reason, update_date, remarks) values 
						('$newoccupancy', '$new_discount', '$oic', '$new_reason', '$now','$remarks');
					";
				mysql_query($sql);
			}
			
			if(isset($_POST['xtra_11']) && $_POST['xtra_11'] > 0) {
				$val= $_POST['xtra_11'];
				$itemid=11;
				$sql = "insert into room_sales (sales_date, order_code, occupancy_id, category_id, item_id,  unit_cost, qty, update_date,update_by,room_id)
				values ('$mynewcheckout', '0', '$newoccupancy', '1' ,'$itemid', '$newunitprice' ,'$val','$now','$user','$newroomid' )";
				mysql_query($sql) or die($sql . mysql_error()) ; 
				$print=true;
			}
			
		}
	}
	
	if($new_halfduration > 0) {
		for($x=0; $x < $new_halfduration;$x++) {
			if($new_duration > 0) {
				$indate = new DateTime(date('Y-m-d H:i:s',strtotime($mynewcheckout."+$hidden_duration hours"))) ;				
			}else{
				if($hidden_duration > 0) {
					$indate = new DateTime(date('Y-m-d H:i:s',strtotime($now."+$hidden_duration hours")));
				}else{
					$indate = new DateTime($now);
				}
			}
			
			//echo '<pre>'. print_r($indate);
			//die($mynewcheckout);
			$hrs = $x * 12;
			$newcheckout2 = date_add($indate, new DateInterval("PT". $hrs ."H") );
			$newcheckout2 = $indate->format("Y-m-d H:i:s");
			$halfrate = $new_rate/2;
			$sql  =" insert into room_sales( occupancy_id, sales_date, category_id, item_id , unit_cost, qty, update_date, remarks,update_by,room_id) 
			values ( '$newoccupancy', '$newcheckout2', 3, 15, '$halfrate',1,'$now','$remarks','$user','$newroomid') ";
			mysql_query($sql) or die($sql);

			// discount
			if($new_discount)
			{
				//$new_discount = -1 * $new_discount;
				$sql  =" insert into room_sales( occupancy_id, sales_date, category_id, item_id ,  unit_cost, qty,update_date,remarks,update_by,room_id) 
					values ('$newoccupancy', '$newcheckout2', 3,17,'$new_discount','1','$now','$remarks','$user','$newroomid') ";
				mysql_query($sql);
				//discount_log
				$sql = "insert into discount_log (occupancy_id, discount_given, oic, reason, update_date, remarks) values 
						('$newoccupancy', '$new_discount', '$oic', '$new_reason', '$now','$remarks');
					";
				mysql_query($sql);
			}
		}
	}
	
	//  extension
	if($new_extension) 
	{
		if($newcheckout2) {
			$addtothis = $newcheckout2;
			$addhours =  12;
		}elseif($mynewcheckout){
			$addtothis = $mynewcheckout;
			$addhours = 24;
		}else{
			$addhours = $hidden_duration;
			$addtothis = $now;
		}
		$extendedcheckout  = date('Y-m-d H:i:s', strtotime("$addtothis +$addhours Hours"));
		$sql  =" insert into room_sales( occupancy_id, sales_date, category_id, item_id , unit_cost, qty, update_date, remarks,update_by,room_id) 
			values ('$newoccupancy', '$extendedcheckout', 3,16,'$hidden_ot_amount','$new_extension','$now','$remarks','$user','$newroomid') ";
		mysql_query($sql);
	}
	
	reset($_POST);
	//$print=false;
	foreach($_POST as $key=>$val) 
	{
		if(substr($key,0,5)=="xtra_" && $val > 0) 
		{
			list($tmp, $itemid)=explode("_", $key);
			if($itemid!=11) {
				$newunitprice=getunitprice($itemid);
				$sql = "insert into room_sales (sales_date, order_code, occupancy_id, category_id, item_id,  unit_cost, qty, update_date, update_by)	values ('$now', '0', '$newoccupancy', '1' ,'$itemid', '$newunitprice' ,'$val','$now' ,'$user')";
				mysql_query($sql) or die($sql . mysql_error()) ; 
				$print=true;
			}
		}
	}
	


	//payments
	
	if( ($new_cash_tendered > 0)  &&  ($new_card_tendered > 0) ) 
	{ 
		$amt_tendered = $new_cash_tendered + $new_card_tendered;

	}
	elseif( ($new_cash_tendered > 0) &&  ($new_card_tendered <= 0) )
	{

		if($new_cash_tendered == $new_amountdue) 
		{
			$sql = " insert into salesreceipts(receipt_date, occupancy_id, tendertype, amount, update_by) 
				values ('$now', '$newoccupancy', 'Cash', '$new_cash_tendered','$user')";
			mysql_query($sql) or die(mysql_error());

			setCurrentCash($new_cash_tendered,'in',$user);
			/*
				set all roomsales items to paid
			*/
			$sql ="update room_sales set status='Paid',update_date = '$now' where occupancy_id='$newoccupancy'";
			mysql_query($sql) or die(mysql_error());
		}
		elseif($new_cash_tendered > $new_amountdue) 
		{
			/*
				insert only enough $new_amountdue
			*/
			$sql = " insert into salesreceipts(receipt_date, occupancy_id, tendertype, amount, update_by) 
				values ('$now', '$newoccupancy', 'Cash', '$new_amountdue','$user')";
			mysql_query($sql) or die(mysql_error());

			setCurrentCash($new_amountdue,'in',$user);
			/*
				set all roomsales items to paid
			*/
			$sql =" update room_sales set status='Paid',update_by='$user', update_date = '".date("Y-m-d H:i:s")."' where occupancy_id='$newoccupancy'";
			mysql_query($sql) or die(mysql_error());
			/*
			insert as deposit the balance from the account
			*/
			$deposit = $new_cash_tendered - $new_amountdue;
			if($new_alreadypayed != '1')
			{
				if($deposit >= 0) {
				$sql = " insert into salesreceipts(receipt_date, occupancy_id, tendertype, amount,update_by) 
					values ('$now', '$newoccupancy', 'Deposit', '$deposit','$user')";
				mysql_query($sql) or die(mysql_error());
				setCurrentCash($deposit,'in',$user);
				}
			}	
		}
	}	
	elseif( ($new_cash_tendered <= 0) &&  ($new_card_tendered > 0) )
	{
		
		if( $new_card_tendered >= $new_amountdue ) {
			$sql = " insert into salesreceipts(receipt_date, occupancy_id, tendertype, amount,update_by) 
				values ('$now', '$newoccupancy', 'Card', '$new_card_tendered','$user')";
			mysql_query($sql) or die(mysql_error());
			$newsalesid = mysql_insert_id();
			$sql ="update room_sales set status='Paid',update_by='$user',update_date = '".date("Y-m-d H:i:s")."' where occupancy_id='$newoccupancy'";
			mysql_query($sql) or die(mysql_error());
			//insert card details
			

			$sql = " insert into card_payment_details (salesreceipt_id, card_type, approval_code, batch_number) 
					values ('$newsalesid','{$_POST["new_card_type"]}','$new_approval_code','$new_batch_number')";
			$fp = fopen("reports/sql.log", "a");
			fwrite( $fp,$sql);
			fclose($fp);

			mysql_query($sql) or die(mysql_error());
		}
	}


	if($print) {
		$obj=new Reporting($newroomid);
		$retval=$obj->printablemos();
		$file = "mos{$room}.txt";
		$fp = fopen("reports/" .$file, "w");
		fwrite( $fp,$retval);
		fclose($fp);
		shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p.bat ' . $file);
	}
	}
	//header("location: ../index.php");
	include_once("class.room.php");
	$rm = new room($newroomid);
	$f = $rm->floor_id-1;
	echo '<script lang="javascript">parent.document.location.href="../index.php?f='. $f .'&room='.$newroomid.'"</script>';
	//echo '{success:true}';
}

function isRoomOccupied($roomid)
{
	$sql = "select status from rooms where room_id = '$roomid'";
	$res = mysql_query($sql);
	list($status)=mysql_fetch_row($res);
	if($status == '2')
	{
		return true;
	}
	return false;
}


?>
